package com.taotao.sso.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.druid.sql.parser.Token;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbUserMapper;
import com.taotao.pojo.TbUser;
import com.taotao.pojo.TbUserExample;
import com.taotao.pojo.TbUserExample.Criteria;
import com.taotao.sso.dao.JedisClient;
import com.taotao.utils.CookieUtils;
import com.taotao.utils.JsonUtils;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private TbUserMapper userMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	
	@Value("${SSO_SESSION_EXPIRE}")
	private Integer SSO_SESSION_EXPIRE;
	@Override
	public TaotaoResult login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
		// TODO Auto-generated method stub
		
		//登录时，从cookie中获取token，与登录信息绑定添加到缓存中
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<TbUser> result = userMapper.selectByExample(example);
		if (result.size()== 0) {
			return TaotaoResult.build(400, "用户还未注册");
		}
		
		TbUser user = result.get(0);
		if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
			return TaotaoResult.build(400, "密码错误");
		}
		String token = UUID.randomUUID().toString();
		
		user.setPassword(null);
		jedisClient.set(REDIS_USER_SESSION_KEY+":"+token, JsonUtils.objectToJson(user));
		jedisClient.expire(REDIS_USER_SESSION_KEY+":"+token, SSO_SESSION_EXPIRE);
		//登陆成功后，获取一个token
		CookieUtils.setCookie(request, response, "TT_TOKEN", token);
		
		return TaotaoResult.ok(token);
	}

	@Override
	public TaotaoResult register(TbUser user) {
		
		//注册成功后，生成一个token，存放在cookie中
		
		user.setUpdated(new Date());
		user.setCreated(new Date());
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		userMapper.insert(user);
		return TaotaoResult.ok();
		
		
	}

	@Override
	public TaotaoResult checkData(String content, Integer type) {
		//创建查询条件
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		//1,2,3 分别代表username，phone，email
		//校验
		if (type == 1) {
			criteria.andUsernameEqualTo(content);
		} else if (type == 2) {
			criteria.andPhoneEqualTo(content);
		} else {
			criteria.andEmailEqualTo(content);
		}
		
		List<TbUser> list = userMapper.selectByExample(example);
		if (list == null || list.size() == 0) {
			return TaotaoResult.ok(true);
		}
		return TaotaoResult.ok(false);
	}

	@Override
	public TaotaoResult getUserByToken(String token) {
		String string = jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);
		if (string == null || string == "") {
			return TaotaoResult.build(400, "session 过期");
		}
		jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
		return TaotaoResult.ok(JsonUtils.jsonToPojo(string, TbUser.class));
	}

	@Override
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		Cookie[] cookies = request.getCookies();
		
		String token = "";
		for (Cookie cookie : cookies) {
			if ("TT_TOKEN".equals(cookie.getName())) {
				token = cookie.getValue();
				break;
			}
		}
		try {
			jedisClient.del(REDIS_USER_SESSION_KEY+":"+token);
			CookieUtils.deleteCookie(request, response, token);
			return "成功退出";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "退出失败";
	}

}
